package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import lombok.var;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Time;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author DJ
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {
        // 处理缓存穿透 1
        // Shop shop = queryWithPassThrough(id);
        // 处理缓存穿透：工具类处理 推荐这种方式
        Shop shop1 = cacheClient.queryWithPassThrough(RedisConstants.CACHE_SHOP_KEY, id, Shop.class,
                this::getById, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);

        // 互斥锁处理缓存击穿
        // Shop shop = queryWithMutex(id);
        // 逻辑过期处理缓存击穿
        // Shop shop = queryWithLogicalExpire(id);
        // 工具类处理 推荐这种方式
        Shop shop = cacheClient.setWithLogicalExpire(id, RedisConstants.CACHE_SHOP_KEY, Shop.class, this::getById, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        if (shop == null) {
            return Result.fail("商铺不存在!");
        }
        // 返回
        return Result.ok(shop);
    }

    /**
     * 推荐手动创建
     */
    public static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 逻辑过期处理缓存击穿
     *
     * @param id 店铺id
     * @return com.hmdp.entity.Shop
     * @author DJ
     * @date 下午11:33 2022/11/20
     **/
    public Shop queryWithLogicalExpire(Long id) {
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        // 从Redis查询商铺缓存 id作为key
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 判断缓存是否存在
        if (StrUtil.isBlank(shopJson)) {
            // 未命中,返回null
            return null;
        }

        // 命中，需要先将缓存进行序列化判断缓存是否过期
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Shop shop = (Shop) redisData.getData();
        LocalDateTime expireTime = redisData.getExpireTime();
        // 未过期返回店铺信息
        if (expireTime.isAfter(LocalDateTime.now())) {
            return shop;
        }

        // 过期，获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        Boolean isLock = tryLock(lockKey);
        // 判断锁获取是否成功
        if (isLock) {
            // 成功，开启独立线程进行缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    saveShop2Redis(id, 20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    // 释放锁
                    unLock(lockKey);
                }
            });
            return shop;
        }
        // 失败，返回店铺信息
        return shop;
    }

    /**
     * 缓存穿透
     *
     * @param id 商铺ID
     * @return com.hmdp.entity.Shop
     * @author DJ
     * @date 下午11:04 2022/11/16
     **/
    public Shop queryWithPassThrough(Long id) {
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        // 从Redis查询商铺缓存 id作为key
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 判断缓存是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            // 存在，直接返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        // 如果是处理缓存穿透的空对象，直接返回
        if (shopJson != null) {
            return null;
        }
        // 不存在，查询数据库商铺信息
        Shop shop = this.getById(id);
        // 判断是否存在，不存在，将空值写入缓存，然后报错
        if (shop == null) {
            // 避免缓存穿透2：将空值写入缓存
            stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        // 存在,写入缓存,设置失效时间
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;
    }


    /**
     * 导入数据库数据到缓存中
     *
     * @param id            店铺id
     * @param expireSeconds 逻辑过期时间
     * @return void
     * @author DJ
     * @date 下午10:52 2022/11/20
     **/
    public void saveShop2Redis(Long id, Long expireSeconds) throws InterruptedException {
        // 查询店铺信息
        Shop shop = this.getById(id);
        Thread.sleep(200);
        // 封装Redis数据对象，添加逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        // 写入Redis
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

    public Shop queryWithMutex(Long id) {
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        // 从Redis查询商铺缓存 id作为key
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 判断缓存是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            // 存在，直接返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        // 如果是处理缓存穿透的空对象，直接返回
        if (shopJson != null) {
            return null;
        }
        Shop shop = null;
        // --------------------- 缓存重建 --------------------- //
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        try {
            // 尝试获取锁
            Boolean isLock = tryLock(lockKey);
            // 判断是否获取锁成功
            if (!isLock) {
                // 不成功，休眠
                Thread.sleep(50);
                // 重试
                queryWithMutex(id);
            }
            // 成功，查询数据写入缓存
            // 不存在，查询数据库商铺信息
            shop = this.getById(id);
            // 模拟重建缓存的延迟
            Thread.sleep(200);
            // 判断是否存在，不存在，将空值写入缓存，然后报错
            if (shop == null) {
                // 避免缓存穿透2：将空值写入缓存
                stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            // 存在,写入缓存,设置失效时间
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 释放锁
            unLock(lockKey);
        }
        return shop;
    }

    /**
     * Redis锁-获取锁
     *
     * @param key 键值
     * @return java.lang.Boolean
     * @author DJ
     * @date 下午11:01 2022/11/16
     **/
    public Boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * Redis锁-释放锁
     *
     * @param key 键值
     * @return void
     * @author DJ
     * @date 下午11:00 2022/11/16
     **/
    public void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺id不能为空");
        }
        // 更新数据库
        this.updateById(shop);
        // 删除缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + shop.getId());
        return Result.ok();
    }
}
